-- UIGD
-- Created by cheny3 Mar/24/2015
-- GD界面

require "game/logic/module/GDM"
require "game/ui/form/gd/UIGDInput1"
require "game/ui/form/gd/UIGDInput2"
require "game/ui/form/gd/activity/UIGDActivityOption"

UIGD = class("UIGD", function()
    return cc.Layer:create();
end);

function UIGD.create()
    return UIGD.new();
end

-- 所有DEBUG项目
local allItems = {"open_dungeon", "dungeon_progress", "hero", "dp", "enter_dungeon",
    "rich", "rich2", "add_attrib", "set_attrib", "copy_item", "active", "full_shovel",
    "rich3", "auto_fight", "invincible_buff", "get_error", "skip_workshop_guide",
    "skip_dungeon_guide"};
-- 迷宫中可以出现的项目
local inDungeonItems = {"add_attrib", "set_attrib", "copy_item", "active", "auto_fight", "invincible_buff",
    "get_error", "skip_workshop_guide", "skip_dungeon_guide"};
-- 项目名称
local itemName = {};

-- 构造函数
function UIGD:ctor()
    self:setName("UIGD");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/setting/GD.csb");
    self.node = node;
    self:addChild(node);

    -- 初始化数据
    self:initData();

    -- 设置层级
    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 100000);

    local scrollview = findChildByName(self.node, "CT/template/scroll_view");
    -- 容器原本的内高
    self.oriHeight = scrollview:getInnerContainerSize().height;

    -- 绘制
    self:redraw(node);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 适配
    self:resize(node);
end

-- 初始化数据
function UIGD:initData()

    local invincibleBuff = self:getInvincibleName();

    -- 获取项目名称
    itemName = {
        ["dp"]   = getLocStr("gd_btn_set_dp"),
        ["hero"] = getLocStr("slime_copy"),
        ["rich"] = getLocStr("gd_btn_rich"),
        ["rich2"]  = getLocStr("gd_btn_rich2"),
        ["active"] = getLocStr("btn_text_activity"),
        ["copy_item"]  = getLocStr("item_copy"),
        ["add_attrib"] = getLocStr("combat_attrib"),
        ["set_attrib"] = getLocStr("gd_set_attrib"),
        ["open_dungeon"]  = getLocStr("map_set"),
        ["enter_dungeon"] = getLocStr("gd_btn_enter_dungeon"),
        ["dungeon_progress"] = getLocStr("dungeon_progress"),
        ["full_shovel"] = getLocStr("gd_btn_add_shovel"),
        ["rich3"] = getLocStr("gd_btn_rich3"),
        ["auto_fight"] = getLocStr("gd_btn_auto_fight"),
        ["invincible_buff"] = invincibleBuff,
        ["get_error"] = getLocStr("get_error"),
        ["skip_workshop_guide"] = getLocStr("skip_workshop_guide"),
        ["skip_dungeon_guide"] = getLocStr("skip_dungeon_guide"),
    };
end

-- 当前页出现的选项
function UIGD:getDebugItems()
    if DungeonM.isInDungeon() then
        return inDungeonItems;
    end
    return allItems;
end

-- 重绘
function UIGD:redraw(node)
    local templateNode = findChildByName(self.node, "CT/template");

    -- 标题
    local titleLabel = findChildByName(templateNode, "title")
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("gd_title"));

    -- 副标题
    local subhead = findChildByName(templateNode, "subhead");
    subhead:setVisible(false);

    -- 绘制项目
    self:redrawItems();
end

-- 设置格子位置
function UIGD:setItemPosition(child, i, textNode, totalHeight)
    local x = (i - 1) % 4 * 125 + 62;
    local y = math.floor((i - 1) / 4) * -160 + totalHeight - 60;
    child:setAnchorPoint(cc.p(0.5, 0.5));
    child:setScale(0.85);
    child:setPosition(cc.p(x, y));
    child:setVisible(true);

    textNode:setAnchorPoint(cc.p(0.5, 0.5));
    textNode:setPosition(cc.p(x, y - 75));
end

-- 绘制项目
function UIGD:redrawItems()
    local itemNode = cc.CSLoader:createNode("layout/workshop/StoreItem.csb");
    local scrollView = findChildByName(self.node, "CT/template/scroll_view");
    local widgetItem = replaceNodeWithWidget(itemNode);

    -- 清空子节点
    scrollView:removeAllChildren();
    scrollView:setVisible(true);

    -- 获取当前可以出现的项目
    local debugItems = self:getDebugItems();

    -- 计算容器高度
    local needHeight = math.ceil(#debugItems / 4) * 160 + 10;
    local totalHeight = math.max(self.oriHeight, needHeight);
    scrollView:setInnerContainerSize(cc.size(scrollView:getInnerContainerSize().width, totalHeight));

    for i = 1, #debugItems do
        local child = widgetItem:clone();
        local textNode = ccui.Text:create();
        self:setItemPosition(child, i, textNode, totalHeight);

        textNode:setName(debugItems[i]);

        child.index = debugItems[i];

        -- 设置图标
        local icon = child:getChildByName("icon");
        local iconPath = getDebugItemPath(child.index);
        icon:loadTexture(iconPath);

        -- 注册点击事件
        self:registerItemTouchEvent(child);

        -- 设置文字
        TextStyleM.setTextStyle(textNode, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_DARK_BROWN);
        textNode:setString(itemName[child.index] or "");

        scrollView:addChild(child);
        scrollView:addChild(textNode);
    end
end

-- 注册项目点击回调
function UIGD:registerItemTouchEvent(node)
    -- 项目背景
    local bg = node:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            bg:setScale(0.9);
        elseif eventType == ccui.TouchEventType.canceled then
            bg:setScale(1.0);
        elseif eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            bg:setScale(1.0);

            self:clickEvent(node.index);
        end
    end
    bg:addTouchEventListener(onClick);
end

-- 点击事件
function UIGD:clickEvent(itemType)
    local form1 = {"open_dungeon", "dungeon_progress", "hero",
        "dp", "copy_item", "enter_dungeon"};
    local form2 = {"add_attrib", "set_attrib"};

    if table.indexOf(form1, itemType) >= 0 then
        -- 两个输入的GD
        UIMgr.getCurrentScene():removeFormByName("UIGDInput1");
        local uiForm = UIGDInput1.create(itemType);
        UIMgr.getCurrentScene():addForm(uiForm);
    elseif table.indexOf(form2, itemType) >= 0 then
        -- 多个输入的GD
        UIMgr.getCurrentScene():removeFormByName("UIGDInput2");
        local uiForm = UIGDInput2.create(itemType);
        UIMgr.getCurrentScene():addForm(uiForm);
    elseif itemType == "rich" then
        -- 高富帅
        GDM.highCoolRich();
    elseif itemType == "rich2" then
        -- 高富帅2
        GDM.highCoolRich2();
    elseif itemType == "active" then
        -- 活动副本
        UIMgr.getCurrentScene():removeFormByName("UIGDActivityOption");
        local uiForm = UIGDActivityOption.create();
        UIMgr.getCurrentScene():addForm(uiForm);
    elseif itemType == "full_shovel" then
        -- 加满镐头数目
        GDM.fullWatchShovels();
    elseif itemType == "rich3" then
        -- 高富帅3
        GDM.highCoolRich3();
    elseif itemType == "auto_fight" then
        if not DEBUG_AUTO then
            alert("AUTO_FIGHT Enabled");
            DEBUG_AUTO = 1;
        else
            alert("AUTO_FIGHT Disabled");
            DEBUG_AUTO = nil;
        end

        local curLevel = UIDungeonMgr.getCurLevel();
        if curLevel then
            curLevel.dungeonTopMenu:showAutoBtn();
        end
    elseif itemType == "invincible_buff" then
        local isOpen = 1;
        if ME.user then
            if ME.user.dbase:query("gd_invincible_buff") == 1 then
                ME.user.dbase:delete("gd_invincible_buff");
                isOpen = 0;
            else
                ME.user.dbase:set("gd_invincible_buff", 1);
                isOpen = 1;
            end
        end

        GDM.invincibleBuff(isOpen);
        local btnStr = self:getInvincibleName();

        self:updateText("invincible_buff", btnStr);
    elseif itemType == "get_error" then
        -- 错误日志
        UIMgr.getCurrentScene():removeFormByName("UIErrorInfo");
        local uiError = UIErrorInfo.create();
        UIMgr.getCurrentScene():addForm(uiError);
    elseif itemType == "skip_workshop_guide" then
        GDM.skipWorkshopGuide();
    elseif itemType == "skip_dungeon_guide" then
        GDM.skipDungeonGuide();
    else
        cclog("error debug type");
    end
end

-- 注册点击事件
function UIGD:registerTouchEvent()
    -- 返回
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIGD");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 适配
function UIGD:resize(node)
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT底部居中并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 更新按钮文字
function UIGD:updateText(btnName, btnStr)
    local scrollView = findChildByName(self.node, "CT/template/scroll_view");
    local textNode = findChildByName(scrollView, btnName);

    if textNode then
        textNode:setString(btnStr);
    end
end

-- 获得无敌的名字
function UIGD:getInvincibleName()
    local btnStr;

    if ME.user and ME.user.dbase:query("gd_invincible_buff") == 1 then
        btnStr = getLocStr("gd_close_invincible_buff");
    else
        btnStr = getLocStr("gd_invincible_buff");
    end

    return btnStr or "";
end